package com.ztgf.commodity.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.common.config.YmlConfig;
import com.ztgf.commodity.mapper.CommoditySpecificationRelationMapper;
import com.ztgf.commodity.models.bo.CommoditySpecificationRelationSaveBO;
import com.ztgf.commodity.models.dto.CommodityArrivalGoodsRemindDTO;
import com.ztgf.commodity.models.dto.CommodityComboRelationDTO;
import com.ztgf.commodity.models.dto.CommoditySpecificationRelationDTO;
import com.ztgf.commodity.models.service.ICommodityArrivalGoodsRemindService;
import com.ztgf.commodity.models.service.ICommodityComboRelationService;
import com.ztgf.commodity.models.service.ICommoditySpecificationRelationService;
import com.ztgf.commodity.models.vo.CommodityAttrPriceVO;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.message.model.bo.MessageAnnouncementSaveBO;
import com.ztgf.message.model.constant.MessageTopicType;
import com.ztgf.message.model.dto.ResponseDTO;
import com.ztgf.message.model.enums.MessageEnum;
import com.ztgf.message.model.service.IKafkaProducerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.*;

/**
 * 商品规格关系表控制器
 *
 * @author chenyu.wang
 * @Date 2020-05-27 10:59:08
 */
@Slf4j
@DubboService
public class CommoditySpecificationRelationServiceImpl extends ServiceImpl<CommoditySpecificationRelationMapper, CommoditySpecificationRelationDTO> implements ICommoditySpecificationRelationService {

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private ICommodityComboRelationService commodityComboRelationService;
    @Autowired
    private ICommodityArrivalGoodsRemindService commodityArrivalGoodsRemindService;
    @DubboReference
    private IKafkaProducerService iKafkaProducerService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据规格id和商品id查询
     *
     * @param goodsId
     * @param atrrIds
     * @return
     */
    @Override
    public CommoditySpecificationRelationDTO selectByCommodityAndAttrIds(Long goodsId, String atrrIds) {
        String[] ids = atrrIds.split(",");
        Arrays.sort(ids);
        String atrr = String.join(",", ids);
        log.info("atrr : {}", atrr);
        return baseMapper.selectByCommodityAndAttrIds(goodsId, atrr);
    }

    /*
     * @description:批量修改库存
     * @author: chenyu.wang
     * @date: 2020-09-03
     */
    @Override
    public boolean batchUpdateInventory(String ids, Integer num) {
        String[] split = ids.split(",");
        for (String id : split) {
            boolean updateInventory = this.updateInventory(Long.valueOf(id), num);
            if (!updateInventory) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean add(CommoditySpecificationRelationSaveBO saveBO) {
        CommoditySpecificationRelationDTO dto = new CommoditySpecificationRelationDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public List<CommoditySpecificationRelationDTO> getByCommodityId(Long id) {
        Wrapper<CommoditySpecificationRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("commodity_id", id);
        return this.selectList(wrapper);
    }

    @Override
    public boolean deleteBatchByGoodsId(Long id) {
        List<CommoditySpecificationRelationDTO> dtos = this.getByCommodityId(id);
        List<Long> ids = new ArrayList<>();
        if (dtos != null && dtos.size() > 0) {
            for (CommoditySpecificationRelationDTO dto : dtos) {
                ids.add(dto.getId());
            }
            return this.deleteBatchIds(ids);
        }
        return false;
    }

    @Override
    public CommodityAttrPriceVO getGoodsSkuPrice(Long goodsId, String attrIds) {
        String ids = getIds(attrIds);
        log.info("******商品规格属性ids****** : {}", ids);
        CommodityAttrPriceVO price = baseMapper.getGoodsSkuPrice(goodsId, ids);
        if (price != null) {
            return price;
        } else {
            //查询商品最低价
            CommodityAttrPriceVO vo = baseMapper.getGoodsMinPrice(goodsId);
            vo.setInventoryNumber(ZERO);
            return vo;
        }
    }

    @Override
    public boolean updateInventory(Long id, Integer num) {
        //查询商品规格，不为空则修改
        CommoditySpecificationRelationDTO dto = this.selectById(id);
        if (dto != null) {
            CommoditySpecificationRelationDTO updateDto = new CommoditySpecificationRelationDTO();
            updateDto.setId(dto.getId());
            updateDto.setInventoryNumber(num);

            boolean update = this.updateById(updateDto);
            if (!update) {
                return false;
            }
            //查询到货提醒表
            List<CommodityArrivalGoodsRemindDTO> list = commodityArrivalGoodsRemindService.queryList(id, dto.getAttrIds());
            if (list != null && list.size() > 0) {
                this.synsToGoodsRemind(list, updateDto.getInventoryNumber());
            }
            //将库存信息放入redis
            redisUtil.saveCommodityNum(dto.getCommodityId(), dto.getAttrIds(), num);
            return true;
        } else {
            //查询商品套餐,不为空则修改
            CommodityComboRelationDTO relationDTO = commodityComboRelationService.selectById(id);
            if (relationDTO != null) {
                CommodityComboRelationDTO updateCombo = new CommodityComboRelationDTO();
                updateCombo.setId(relationDTO.getId());
                updateCombo.setInventoryNumber(num);
                boolean update = commodityComboRelationService.updateById(updateCombo);
                if (!update) {
                    return false;
                }
                //查询到货提醒表
                List<CommodityArrivalGoodsRemindDTO> list = commodityArrivalGoodsRemindService.queryList(id, String.valueOf(relationDTO.getId()));
                if (list != null && list.size() > 0) {
                    this.synsToGoodsRemind(list, updateCombo.getInventoryNumber());
                }
                //将库存信息放入redis
                redisUtil.saveCommodityNum(relationDTO.getCommodityId(), relationDTO.getId().toString(), num);
                return true;
            }
        }
        return false;
    }

    /**
     * description: 异步处理到货提醒并发送系统消息
     * param: [goodsId, ids]
     * author: chenyu.wang
     * date: 2020-06-23
     * return: void
     */
    @Async
    public void synsToGoodsRemind(List<CommodityArrivalGoodsRemindDTO> list, Integer num) {
        for (CommodityArrivalGoodsRemindDTO dto : list) {
            if (num > dto.getBuyNum()) {
                this.sendMsg(dto.getShopId(), "商品到货提醒", "您关注的商品已到货!", 0L, ONE);
                //发送消息之后删除记录
                commodityArrivalGoodsRemindService.deleteById(dto.getId());
            }
        }
    }

    /**
     * @description:发送站内信
     * @author: chenyu.wang
     * @date: 2020-10-09
     * @return:
     */
    @Async
    public void sendMsg(Long shopId, String title, String content, Long orderId, Integer shopType) {
        ResponseDTO responseDTO = new ResponseDTO();
        responseDTO.setMessageId(shopId + "");
        MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
        messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
        messageAnnouncementSaveBO.setShopId(shopId);
        messageAnnouncementSaveBO.setTitle(title);
        messageAnnouncementSaveBO.setContent(content);
        messageAnnouncementSaveBO.setTextType(1);
        messageAnnouncementSaveBO.setJumpType(MessageEnum.ORDER_STATUS_CHANGE.getCode() + "");
        if (shopType == ONE) {//买家
            messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_1.getCode());
        } else {//卖家
            messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_2.getCode());
        }
        messageAnnouncementSaveBO.setKey(orderId + "");
        responseDTO.setData(messageAnnouncementSaveBO);
        iKafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
    }
}
